// pages/duesDetails/duesDetails.js
const app = getApp();
const util = require("../../utils/util.js");
var WxParse = require('../../wxParse/wxParse.js');
var timestamp = Date.parse(new Date()) / 1000; 
const CryptoJS = require('../../utils/aes-jia.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail:{},
    duesmore:false,
    list:[],
    list1: [],
    active: 0,
    pageNumber:1,
    pageNumber1:1,
    total:0,
    total1:0,
    totalPages:1,
    totalPages1:1,
    payment: 1,
    show:false,
    paymentAmount:0,
    today:'',
    success:false,
    sharePicUrl:'',
    id:'',
    whetherSetPayPwd:'',
    balance:0,
    showPayPwdInput: false,  //是否展示密码输入层
    pwdVal: '',  //输入的密码
    payFocus: true, //文本框焦点
    prepaymentRecordId:'',
    isOver: true,
    detailid:'',
    willShare: false,
    willShare1: false,
    isapp:false,
    loginShow: false,
    login: false,
    phone: false,
    phoneshow: false,
  },
  login() {
    if (this.data.login) {
      this.toggle('phoneshow', true)
      this.selectComponent('#phone').showClose()
    } else {
      this.toggle('loginShow', true)
      this.selectComponent('#login').showClose()
    }
  },
  loginClose() {
    this.toggle('loginShow', false)
  },
  toggleToast(e) {
    console.log(e.detail)
    if (!e.detail.loginShow) {
      this.toggle('loginShow', false)
    }
    this.refreshData()
  },
  toggleToast1(e) {
    console.log(e.detail)
    if (!e.detail.phoneshow) {
      this.toggle('phoneshow', false)
    }
    this.refreshData()
  },
//详情
  getdetail(){
    var that = this
    app.req({
      url:'orgmini/dueNotice/info',
      data: {
        id: that.data.id
      },
      success: function (res) {
        if (200 == res.code) {
          for (let i of res.data.details) {
            i.feeLevel = that.toChinesNum(i.feeLevel)
          }
          res.data.createTime = util.itemDateToShow(res.data.createTime, 1, true, false).substring(5);
          if (res.data.isJoin==0){
            wx.showModal({
              title: '提示',
              content: '此内容仅组织内成员可查看',
              showCancel:false,
              confirmColor:'#2168eb',
              success(res) {
                if (res.confirm) {
                    wx.switchTab({
                      url: '/pages/newIndex/newIndex'
                    })
                }
              }
            })
          }else{
            that.toggle("detail", res.data)
            var rich = res.data.content
            that.toggle('rich', rich)
            WxParse.wxParse('rich', 'md', rich, that, 5);
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      }
    });
  },
  tabshow(e){
    var that = this
    var tab = e.currentTarget.dataset.tab
    if(tab!=that.data.active){
      that.toggle('active', tab)
    }
  },
  getlist(){
    var that = this
    app.req({
      url: 'orgmini/dueRecord/payList',
      data: {
        noticeId: that.data.id,
        pageSize: 10,
        pageNumber: that.data.pageNumber,
        type: 1
      },
      success: function (res) {
        if (200 == res.code) {
          if (that.data.pageNumber == 1) {
            that.toggle("list", res.data.rows)
          } else {
            that.toggle("list", that.data.list.concat(res.data.rows))
          }
          that.toggle("total", res.data.total)
          that.toggle("totalPages", res.data.totalPages)
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      }
    });
  },
  getlist1() {
    var that = this
    app.req({
      url: 'orgmini/dueRecord/payList',
      data: {
        noticeId: that.data.id,
        pageSize: 10,
        pageNumber: that.data.pageNumber1,
        type: 2
      },
      success: function (res) {
        if (200 == res.code) {
          if (that.data.pageNumber1==1){
            that.toggle("list1", res.data.rows)
          }else{
            that.toggle("list1", that.data.list1.concat(res.data.rows))
          }
          that.toggle("total1", res.data.total)
          that.toggle("totalPages1", res.data.totalPages)
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      }
    });
  },
  duesmore(){
    var that = this
    that.toggle("duesmore", !that.data.duesmore)
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  pay(e){
    var that = this
    var amount = e.currentTarget.dataset.amount
    var detailid = e.currentTarget.dataset.detailid
    that.toggle('paymentAmount', amount)
    that.toggle('detailId', detailid)
    that.toggle('show', true)
    var today = util.formatTime3(new Date()).substring(0, 10);
    that.toggle('today', today)
    let headIcon = '';
    let logo = '';
    let img = ''
    that.getHead().then(headUrl => {
      console.log(headUrl);
      headIcon = headUrl
      return that.getLogo();
    }).then(logoUrl => {
      console.log(logoUrl);
      logo = logoUrl;
      return that.getImg();
    }).then(imgUrl => {
      console.log(imgUrl);
      img = imgUrl;
      that.drawImg(logo, headIcon, img);
    })
  },
  payment(e) {
    var id = e.currentTarget.dataset.index
    this.toggle('payment', id)
  },
  onClose: function () {
    this.setData({
      show: false,
      success:false,
      isapp:false
    });
  },
  contact: function (e) {
    console.log(e);
  },
  //预支付
  operationRecord() {
    let that = this
    var payPwd = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.pwdVal)
    var amount = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.paymentAmount)
    console.log('预支付参数', payPwd, amount)
    app.req({
      url: "orgmini/wxpay/operationRecord",
      method: "post",
      data: {
        payPwd: payPwd,
        amount: amount
      },
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            prepaymentRecordId: res.msg,
            pwdVal: ''
          });
          console.log('预支付', that.data.prepaymentRecordId)
          that.addToActivity(0)
        } else {
          that.setData({
            pwdVal: ''
          });
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //支付
  addToActivity: function (e) {
    var that = this;
    if (that.data.isOver) {
      that.setData({
        isOver: false
      })
      var payWay = '';
      if (e == 0) {
        payWay = 0
      } else {
        payWay = e.currentTarget.dataset.id;
      }
      console.log("支付方式", payWay)
      var data = that.data;
      console.log("会费ssssss", that.data.paymentAmount)
      app.req({
        url: "orgmini/dueRecord/pay",
        method: "post",
        data: {
          prepaymentRecordId: that.data.prepaymentRecordId,
          noticeId:that.data.id,
          amount: that.data.paymentAmount,
          payWay: payWay,
          detailId: that.data.detailId
        },
        success: function (res) {
          console.log("支付", that.data.paymentAmount, res)
          if (res.code == 200 && payWay == 0) {
            that.setData({
              show: false,
              isOver: true,
              success:true
            })
            that.onShow()
            
          } else if (res.code == 200 && payWay == 1) {
            var paydata = res.data;
            console.log("调取", paydata)
            wx.requestPayment({
              timeStamp: paydata.prepayDate.timeStamp,
              nonceStr: paydata.prepayDate.nonceStr,
              package: 'prepay_id=' + paydata.prepayDate.prepay_id,
              signType: 'MD5',
              paySign: paydata.prepayDate.paySign,
              success(res) {
                that.setData({
                  show: false,
                  isOver: true,
                  success: true
                })
                that.onShow()
              },
              fail(res) {
                that.setData({
                  isOver: true,
                })
                console.log("支付已取消")
                console.log(res.errMsg)
              }
            })
          } else {
            that.setData({
              isOver: true,
              isOpen: false,
            })
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      });
    }
  },
  addToActivity1(e) {
    var that = this;
    var payWay = e.currentTarget.dataset.id;
    if (payWay == 0) {
      if (that.data.balance < that.data.paymentAmount) {
        wx.showToast({
          title: "钱包余额不足",
          icon: 'none',
          duration: 2000
        })
        return
      } else {
        if (that.data.whetherSetPayPwd) {
          that.setData({
            showPayPwdInput: true,
            payFocus: true,
          })
        } else {
          wx.showModal({
            title: '温馨提示',
            content: '为了您的账号安全，请前往APP设置支付密码',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                // wx.navigateTo({
                //   url: '/pages/password/password',
                // })
              }
            }
          })
        }
      }
    }
  },
  // 支付密码
  /**
   * 隐藏支付密码输入层
   */
  hidePayLayer: function () {
    this.setData({
      pwdVal: '',
      showPayPwdInput: false,
      payFocus: false
    })

  },
  /**
   * 获取焦点
   */
  getFocus: function () {
    this.setData({ payFocus: true });
  },
  /**
   * 输入密码监听
   */
  inputPwd: function (e) {
    this.setData({ pwdVal: e.detail.value });
    if (this.data.pwdVal.length >= 6) {
      this.setData({
        showPayPwdInput: false,
        payFocus: false
      });
      this.operationRecord()
    }
  },

  // 打开文档
  openFile(e) {
    var dataset = e.currentTarget.dataset;
    // console.log(dataset.url);
    wx.downloadFile({
      url: dataset.url,
      success: function (res) {
        var filePath = res.tempFilePath
        // console.log(filePath);
        wx.openDocument({
          filePath: filePath,
          success: function (res) { }
        })
      }
    })
  },
  //获取发起人
  getHead() {
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: this.data.detail.currentUserAvatarUrl,
        success: res => {
          resolve(res.tempFilePath);
        },
        fail: (err) => {
          console.log(er)
        }
      })
    })
  },
  //获取logo
  getLogo() {
    var img = 'https://img.yiqilaiwang.com/tmp/wxa0535d31b27c14d8.o6zAJs2b9caL0xH8yzIUilWRbI6Y.vfJ2kwhyWHRX1968329d9d820dd991428da6ede4c5f8.png'
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url:img,
        success: res => {
          resolve(res.tempFilePath);
        },
        fail: (err) => {
          console.log(er)
        }
      })
    })
  },
  getImg() {
    var img = 'https://img.yiqilaiwang.com/tmp/wxa0535d31b27c14d8.o6zAJs2b9caL0xH8yzIUilWRbI6Y.gKrGOYXdT42wd3b49e9b38392aa86a61777874c87d25.png'
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url:img,
        success: res => {
          resolve(res.tempFilePath);
        },
        fail: (err) => {
          console.log(er)
        }
      })
    })
  },
//绘图
  drawImg(logo, headIcon, img) {
    let name = this.data.detail.currentUserName
    let orgname = this.data.detail.orgName
    let time = this.data.today
    let w = 0;
    wx.getSystemInfo({
      success: function (res) {
        w = res.screenWidth;
      },
    })
    let ctx = wx.createCanvasContext('shareFrends'); 
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, w / 750 * 480 * 2, w / 750 * 500 * 2);
    ctx.drawImage(logo, w / 750 * 430 * 2, w / 750 * 5 * 2, w / 750 * 38 * 2, w / 750 * 44 * 2, 0, 0)
    //画一个圆形裁剪区域
    ctx.save()//保存当前的绘图上下文。
    ctx.beginPath()//开始创建一个路径
    ctx.arc(w / 750 * 63 * 2, w / 750 * 40 * 2, w / 750 * 30 * 2, 0, 2 * Math.PI, false)
    ctx.clip()//裁剪
    //绘制图片
    ctx.drawImage(headIcon, w / 750 * 32 * 2, w / 750 * 10 * 2, w / 750 * 60 * 2, w / 750 * 60 * 2)
    ctx.restore()
    ctx.setFontSize(w / 750 * 24 * 2)
    ctx.setFillStyle('#333333');
    ctx.fillText(name, w / 750 * 105 * 2, w / 750 * 40 * 2)
    ctx.drawImage(img, w / 750 * 150 * 2, w / 750 * 110 * 2, w / 750 * 176 * 2, w / 750 * 105 * 2,0,0)
    ctx.setFontSize(w / 750 * 30 * 2)
    ctx.setFillStyle('#333333');
    ctx.fillText('缴费成功', w / 750 * 165 * 2, w / 750 * 270 * 2)
    ctx.setFontSize(w / 750 * 20 * 2)
    ctx.setFillStyle('#999999');
    ctx.fillText('缴费组织：' + orgname, w / 750 *125 * 2, w / 750 * 320 * 2)
    ctx.fillText('缴费时间：' + time, w / 750 * 125 * 2, w / 750 * 350 * 2)
    ctx.draw(false, () => {
      //调用接口将画布转换为图片
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        fileType: 'jpg',
        quality: 1,
        width: w / 750 * 480 * 2,
        height: w / 750 * 500 * 2,
        destWidth: w / 750 * 480 * 2,
        destHeight: w / 750 * 500 * 2,
        canvasId: 'shareFrends',
        success: res => {

          wx.hideToast();

          this.setData({
            sharePicUrl: res.tempFilePath //生成的图片路径
          }, () => {

            //渲染完后再显示分享海报
            this.setData({
              share: false,
              showSharePic: true
            })

          })
          console.log('图片路径', this.data.sharePicUrl)
        },
        fail(err) {
          wx.showToast({
            title: '图片生成失败，请稍候再试！',
            icon: 'none',
            mask: true
          })
        }
      })
    });
  },
  //保存图片
  savePic() {
    let sharePicUrl = this.data.sharePicUrl;
    console.log('保存1111', sharePicUrl)
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.writePhotosAlbum'] == false) {
          wx.showModal({
            title: '提示',
            content: '是否授权将相册保存到相册？',
            confirmColor: '#2ca2ed',
            success: res => {
              //点击确定打开授权设置
              if (res.confirm) {

                wx.openSetting({
                  success: res => {

                    setTimeout(() => {
                      if (res.authSetting['scope.writePhotosAlbum'] == true) {

                        wx.saveImageToPhotosAlbum({
                          filePath: sharePicUrl,
                          success: res => {
                            wx.showToast({
                              title: '保存成功！',
                              icon: 'success',
                              mask: true
                            })
                            this.toggle('success',false)
                          },
                          fail: err => {
                            wx.showToast({
                              title: '图片生成中，请稍后再试',
                              icon: 'none',
                              mask: true
                            })
                          }
                        })

                      } else {
                        wx.showToast({
                          title: '图片生成中，请稍后再试',
                          icon: 'none',
                          mask: true
                        })
                      }
                    }, 500)

                  }
                })

              }

            }
          })
        } else {
          console.log('保存22222', sharePicUrl)
          wx.saveImageToPhotosAlbum({
            filePath: sharePicUrl,
            success: res => {
              wx.showToast({
                title: '保存成功！',
                icon: 'success',
                mask: true
              })
              this.toggle('success',false)
            },
            fail: err => {
              console.log('保存22222', err)
              wx.showToast({
                title: '授权失败',
                icon: 'none',
                mask: true
              })
            }
          })

        }
      }
    })

  },
  //获取是否有密码
  getIspswd() {
    var that = this
    app.req({
      url: 'orgmini/user/whetherSetPayPwd',
      data: {
      },
      method: 'POST',
      success: function (res) {
        console.log('密码', res);
        if (res.code == 200) {
          that.setData({
            whetherSetPayPwd: res.data.whetherSetPayPwd
          })
        }
      }
    })
  },
  balance: function () {
    var that = this;
    app.req({
      url: "orgmini/account/expenseCalendars",
      data: {
        pageNumber: 1,
        pageSize: 1
      },
      success: function (res) {
        if (200 == res.code) {
          var balance = res.data.balance || 0;
          that.toggle("balance", balance);
        }
      }
    });
  },
  isapp(){
    this.toggle('isapp',true)
  },
  refreshData: function () {
    var that = this;
    wx.getSetting({
      success(res) {
        // if (!res.authSetting['scope.userInfo'] || wx.getStorageSync('uid') == '') {
        if (wx.getStorageSync('uid') == '') {
          that.toggle("login", false);
          that.login()
        } else {
          that.toggle("login", true);
          var phone = wx.getStorageSync("phone")
          if (phone == '') {
            that.toggle("phone", true);
            that.login()
          } else {
            that.toggle("phone", false);
            that.getdetail()
            that.getlist()
            that.getlist1()
            that.getIspswd()
            that.balance()
          }
        }
      },
    })

  },
  // 数字转换
  toChinesNum(num) {
    let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    let unit = ["", "十", "百", "千", "万"];
    num = parseInt(num);
    let getWan = (temp) => {
      let strArr = temp.toString().split("").reverse();
      let newNum = "";
      for (var i = 0; i < strArr.length; i++) {
        newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
      }
      return newNum;

    }
    let overWan = Math.floor(num / 10000);
    let noWan = num % 10000;
    if (noWan.toString().length < 4) {
      noWan = "0" + noWan;
    }
    return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.toggle('id', options.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    that.setData({
      pageNumber:1,
      pageNumber1:1
    })
    that.toggle('willShare', false)
    that.toggle('willShare1', false)
    that.refreshData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this
    if (that.data.active==0) {
      if (that.data.totalPages > that.data.pageNumber){
        that.toggle("pageNumber", that.data.pageNumber + 1);
        that.getlist();
      }
    } else if (that.data.active == 1) {
      if (that.data.totalPages1 > that.data.pageNumber1) {
        that.toggle("pageNumber1", that.data.pageNumber1 + 1);
        that.getlist1();
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    this.toggle("success", false);
    var title= ''
    if (e.target.dataset.type==0){
      this.toggle("willShare", true);
      title = '会费通知:' + this.data.detail.newsDigest
      
    }else{
      this.toggle("willShare1", true);
      title = '缴费成功'
    }
    return {
      title: title,
      success(e) {
        console.log("分享成功了")
      },
      fail(e) {
        console.log("分享失败")
      }
    }
  }
})